<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="分配角色">
      <el-form :model="form">
        <el-form-item label="用户姓名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" disabled />
        </el-form-item>

        <el-form-item label="职位列表" :label-width="formLabelWidth">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
            <el-checkbox v-for="role in roles" :key="role.id" :label="role">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save($parent)"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { RoleData, User } from '@/utils/api/acl/user/type'
import { reqAllRole, reqSetUserRole } from '@/utils/api/acl/user'
import { reactive, ref } from 'vue'

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 用户姓名

const form = reactive({
  username: ''
})

const userId = ref<number>()

// 多选框
const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedRoles = ref<RoleData[]>([])
const roles = ref<RoleData[]>([])

// 是否显示对话框
const changeShow = (row: User) => {
  userId.value = row.id
  form.username = row.username!
  getRole(row.id!)
  dialogFormVisible.value = true
}

// 获取该用户的角色
const getRole = async (userId: number) => {
  const res = await reqAllRole(userId)
  if (res.data.code == 200) {
    roles.value = res.data.data.allRolesList
    checkedRoles.value = res.data.data.assignRoles
  }
}

// 全选
const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? roles.value : []
  isIndeterminate.value = false
}

// 单选
const handleCheckedRolesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}

// 保存分配的权限
const save = async ($parent: any) => {
  const roleIdList: number[] = []
  checkedRoles.value.forEach((item: RoleData) => {
    roleIdList.push(item.id!)
  })

  const res = await reqSetUserRole({ roleIdList, userId: userId.value! })
  if (res.data.code == 200) {
    ElMessage.success('分配成功')
    $parent.$parent.getUserData()
    dialogFormVisible.value = false
  }
}

defineExpose({ changeShow })
</script>

<style scoped></style>
